package com.examination.to.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.to.entity.Answer;
import com.examination.to.entity.Exam;
import com.examination.to.entity.Question;
import com.examination.to.mapper.AnswerMapper;
import com.examination.to.mapper.ExamMapper;
import com.examination.to.mapper.QuestionMapper;
import com.examination.to.service.ExamService;
import com.examination.to.util.Result;
import com.examination.to.vo.QuestionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * auther:FC
 * date:2021/5/10
 */
@Service
@Slf4j
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private AnswerMapper answerMapper;

    public Result createExam(Exam exam){
        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        try {
            if (examMapper.findlast() == null){
                exam.setId(1);
            }else {
                Exam elast = examMapper.findlast();
                Integer eid = elast.getId();
                exam.setId(++eid);
                log.info(exam.getDuration().toString());
            }
            examMapper.insert(exam);
            result.setCode(200);
            result.setMsg("创建试卷成功");
            result.setDetail(exam);
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    public Result updateExam(Exam exam){
        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        try{
            Exam existexam = examMapper.findById(exam);
            if (existexam != null){
                examMapper.updateById(exam);
                result.setCode(200);
                result.setMsg("修改成功");
                result.setDetail(exam);
            }else{
                result.setMsg("考试不存在");
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    public Result deleteExam(Exam exam){
        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        try {
            Exam existexam = examMapper.findById(exam);
            if (existexam != null){
                examMapper.deleteById(exam);
                QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("examid",exam.getId());
                List<Question> questions = questionMapper.selectList(queryWrapper);
                for (Question question : questions) {
                    questionMapper.deleteById(question.getId());
                }
                QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
                answerQueryWrapper.eq("examid",exam.getId());
                List<Answer> answers = answerMapper.selectList(answerQueryWrapper);
                for (Answer answer : answers) {
                    answerMapper.deleteById(answer.getId());
                }
                result.setCode(200);
                result.setMsg("删除成功");
                result.setDetail(exam);
            }else {
                result.setMsg("该考试不存在");
            }
        }catch (Exception e){
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    public List<Exam> examList(){

        return examMapper.selectList(new QueryWrapper<>());
    }

    public Result showExam(Integer examid){
        return null;
    }

    /**
     * 该方法为二次编辑页面的试题保存
     * 主要逻辑为
     * 1、当新建的试卷为空时，往里加题目
     * 2、不为空时根据发送过来的试题比对
     * 创建时的试卷更改响应内容
     * 3、用户添加题目时，比对创建时的题目
     * 完毕后再执行一个批量添加试题的逻辑
     * 总结：主要就是一个修改并添加的简单逻辑
     * 但是处理起来比较繁琐，ps（经验较少）
     * 写的代码行数严重超标不够规范，这也是后续
     * 我需要完善的地方，尽可能的封装重复的代码
     * 精简代码行数，增加方法、代码的可读性
     * @param id
     * @param questionVos
     * @return
     */
    public Result issueAndshow(Integer id,List<QuestionVo> questionVos){
        Result result = new Result();
        result.setCode(-1);
        result.setDetail(null);
        if (questionVos == null){
            result.setMsg("所传列表为空");
            return result;
        }
        Integer index = 0;
        QueryWrapper queryWrapper =  new QueryWrapper();
        queryWrapper.eq("examid",id);
        List<Question> questions = questionMapper.selectList(queryWrapper);
        try {
            if (questions.size() == 0){
                for (QuestionVo questionVo : questionVos) {
                    Question question = new Question();
                    question.setScore(questionVo.getScore());
                    question.setStuinfo(questionVo.getStuinfo());
                    Question last = questionMapper.findLast();
                    if (last == null){
                        question.setId(1);
                    }else {
                        Integer lastid = last.getId();
                        question.setId(++lastid);
                    }
                    question.setExamid(id);
                    question.setQutype(questionVo.getQuestiontype());
                    question.setLevel(questionVo.getQuestionlevel());
                    question.setQucontent(questionVo.getQuestioncontent());
                    question.setCreateperson(questionVo.getCreateperson());
                    question.setAnalysis(questionVo.getAnalysis());
                    questionMapper.insert(question);
                    StringBuffer mutiplechoice = new StringBuffer();
                    if (questionVo.getQuestiontype() != 4 & questionVo.getQuestiontype() < 4){
                        Answer answer = new Answer();
                        answer.setExamid(id);
                        Question last2 = questionMapper.findLast();
                        Integer lastid1 = last2.getId();
                        answer.setQuestionid(lastid1);
                        StringBuffer answers = new StringBuffer();
                        for (int i = 0;i<questionVo.getAnswer().length;i++){
                            answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                            if (questionVo.getQuestiontype() == 2){
                                if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                    mutiplechoice.append(i).append(",");
                            }else {
                                if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                    answer.setTrueoption(i + "");
                            }
                        }
                        if (questionVo.getQuestiontype() == 3){
                            StringBuffer stringBuffer = new StringBuffer();
                            for (int i=0;i<questionVo.getAnswer().length;i++){
                                if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                    stringBuffer.append("True").append(",");
                                else stringBuffer.append("false").append(",");
                                answer.setJudge(stringBuffer.toString());
                            }
                        }

                        if (questionVo.getQuestiontype() == 2){
                            answer.setTrueoption(mutiplechoice.toString().substring(0,mutiplechoice.toString().length() - 1));
                        }
                        String handleAnswers = answers.toString();
                        if (handleAnswers.length() != 0)
                            handleAnswers = handleAnswers.substring(0,handleAnswers.length() - 1);
                        answer.setAlloptions(handleAnswers);
                        answerMapper.insert(answer);
                    }else if (questionVo.getQuestiontype() == 4){
                        Answer answer = new Answer();
                        Question last1 = questionMapper.findLast();
                        Integer lastid1 = last1.getId();
                        answer.setQuestionid(lastid1);
                        answer.setExamid(id);
                        answer.setText(questionVo.getAnswer()[0].getAnswer());
                        answer.setAnalysis(questionVo.getAnalysis());
//                        answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
                        answerMapper.insert(answer);
                    }else if (questionVo.getQuestiontype() == 5){
                        question.setScore(null);
                        question.setStuinfo(questionVo.getStuinfo());
                        questionMapper.updateById1(question);
                    }else if (questionVo.getQuestiontype() == 6){
                        Answer answer = new Answer();
                        Question last1 = questionMapper.findLast();
                        Integer lastid1 = last1.getId();
                        answer.setQuestionid(lastid1);
                        answer.setExamid(id);
//                        answer.setText(questionVo.getAnswer()[0].getText());
                        answer.setAnalysis(questionVo.getAnalysis());
//                        answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
                        answerMapper.insert(answer);
                    }

                }
            } else {
                Integer k = 0;
                for (QuestionVo questionVo : questionVos) {
                    Question question = new Question();
                    Question index1 = index < questions.size() ? questions.get(index++) : null;
                    if (index1 != null){
                        question.setCreateperson(questionVo.getCreateperson());
                        question.setQucontent(questionVo.getQuestioncontent());
                        question.setQutype(questionVo.getQuestiontype());
                        question.setExamid(id);
                        question.setId(index1.getId());
                        question.setStuinfo(questionVo.getStuinfo());
                        question.setScore(questionVo.getScore());
                        questionMapper.updateById1(question);
                        StringBuffer mutiplechoice = new StringBuffer();
                        if (questionVo.getQuestiontype() != 4 & questionVo.getQuestiontype() < 4) {
                            Answer answer = new Answer();
                            QueryWrapper<Answer> wrapper1 = new QueryWrapper<>();
                            wrapper1.eq("examid",id);
                            List<Answer> answerss = answerMapper.selectList(wrapper1);
                            Answer index2 = answerss.get(k);
                            answer.setId(index2.getId());
                            answer.setExamid(id);
                            answer.setQuestionid(index1.getId());
                            StringBuffer answers = new StringBuffer();
                            for (int i = 0; i < questionVo.getAnswer().length; i++) {
                                answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                                if (questionVo.getQuestiontype() == 2) {
                                    if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                        mutiplechoice.append(i).append(",");
                                } else {
                                    if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                        answer.setTrueoption(i + "");
                                }
                            }
                            if (questionVo.getQuestiontype() == 3){
                                StringBuffer stringBuffer = new StringBuffer();
                                for (int i=0;i<questionVo.getAnswer().length;i++){
                                    if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                        stringBuffer.append("True").append(",");
                                    else stringBuffer.append("false").append(",");
                                    answer.setJudge(stringBuffer.substring(0,stringBuffer.length() - 1));
                                }
                            }
                            if (questionVo.getQuestiontype() == 2) {
                                answer.setTrueoption(mutiplechoice.toString().substring(0, mutiplechoice.toString().length() - 1));
                            }
                            String handleAnswers = answers.toString();
                            if (handleAnswers.length() != 0)
                                handleAnswers = handleAnswers.substring(0, handleAnswers.length() - 1);
                            answer.setAlloptions(handleAnswers);
                            answerMapper.updateById2(answer);
                        }else if (questionVo.getQuestiontype() == 4){
                            Answer answer = new Answer();
                            QueryWrapper<Answer> wrapper1 = new QueryWrapper<>();
                            wrapper1.eq("examid",id);
                            List<Answer> answerss = answerMapper.selectList(wrapper1);
                            Answer index2 = answerss.get(k);
                            answer.setId(index2.getId());
                            answer.setQuestionid(index1.getId());
                            answer.setExamid(id);
                            answer.setText(questionVo.getAnswer()[0].getAnswer());
                            answer.setAnalysis(questionVo.getAnalysis());
//                            answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
                            answerMapper.updateById2(answer);
                        }else if (questionVo.getQuestiontype() == 5){
                            question.setScore(null);
                            question.setStuinfo(questionVo.getStuinfo());
                            questionMapper.updateById1(question);
                            k--;
                        }else if (questionVo.getQuestiontype() == 6){
//                            Answer answer = new Answer();
//                            QueryWrapper<Answer> wrapper1 = new QueryWrapper<>();
//                            wrapper1.eq("examid",id);
//                            List<Answer> answerss = answerMapper.selectList(wrapper1);
//                            Answer index2 = answerss.get(k);
//                            answer.setId(index2.getId());
//                            answer.setQuestionid(questions.get(k).getId());
//                            answer.setExamid(id);
//                            answer.setText(questionVo.getAnswer()[0].getText());
//                            answer.setAnalysis(questionVo.getAnalysis());
//                            answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
//                            answerMapper.updateById2(answer);
                            k--;
                        }
                        k++;
                    }else {
                        QueryWrapper query =  new QueryWrapper();
                        queryWrapper.eq("examid",id);
                        List<Question> questionList =questionMapper.selectList(query);
                        Question last = questionList.get(questionList.size()-1);
                        Integer lastid = last.getId();
                        question.setScore(questionVo.getScore());
                        question.setStuinfo(questionVo.getStuinfo());
                        question.setId(++lastid);
                        question.setExamid(id);
                        question.setQutype(questionVo.getQuestiontype());
                        question.setLevel(questionVo.getQuestionlevel());
                        question.setQucontent(questionVo.getQuestioncontent());
                        question.setCreateperson(questionVo.getCreateperson());
                        question.setAnalysis(questionVo.getAnalysis());
                        questionMapper.insert(question);
                        StringBuffer mutiplechoice = new StringBuffer();
                        if (questionVo.getQuestiontype() != 4 & questionVo.getQuestiontype() < 4){
                            Answer answer = new Answer();
                            answer.setExamid(id);
                            Question last2 = questionMapper.findLast();
                            Integer lastid1 = last2.getId();
                            answer.setQuestionid(lastid1);
                            StringBuffer answers = new StringBuffer();
                            for (int i = 0;i<questionVo.getAnswer().length;i++){
                                answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                                if (questionVo.getQuestiontype() == 2){
                                    if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                        mutiplechoice.append(i).append(",");
                                }else {
                                    if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                        answer.setTrueoption(i + "");
                                }
                            }
                            if (questionVo.getQuestiontype() == 3){
                                StringBuffer stringBuffer = new StringBuffer();
                                for (int i=0;i<questionVo.getAnswer().length;i++){
                                    if (questionVo.getAnswer()[i].getIstrue().equals("True"))
                                        stringBuffer.append("True").append(",");
                                    else stringBuffer.append("false").append(",");
                                    answer.setJudge(stringBuffer.substring(0,stringBuffer.length() - 1));
                                }
                            }

                            if (questionVo.getQuestiontype() == 2){
                                answer.setTrueoption(mutiplechoice.toString().substring(0,mutiplechoice.toString().length() - 1));
                            }
                            String handleAnswers = answers.toString();
                            if (handleAnswers.length() != 0)
                                handleAnswers = handleAnswers.substring(0,handleAnswers.length() - 1);
                            answer.setAlloptions(handleAnswers);
                            answerMapper.insert(answer);
                        }else if (questionVo.getQuestiontype() == 4){
                            Answer answer = new Answer();
                            Question last1 = questionMapper.findLast();
                            Integer lastid1 = last1.getId();
                            answer.setQuestionid(lastid1);
                            answer.setExamid(id);
                            answer.setText(questionVo.getAnswer()[0].getText());
                            answer.setAnalysis(questionVo.getAnalysis());
                            answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
                            answerMapper.insert(answer);
                        }else if (questionVo.getQuestiontype() == 5){
                            question.setScore(null);
                            question.setStuinfo(questionVo.getStuinfo());
                            questionMapper.updateById1(question);
                        }else if (questionVo.getQuestiontype() == 6){
                            Answer answer = new Answer();
                            Question last1 = questionMapper.findLast();
                            Integer lastid1 = last1.getId();
                            answer.setQuestionid(lastid1);
                            answer.setExamid(id);
                            answer.setText(questionVo.getAnswer()[0].getText());
                            answer.setAnalysis(questionVo.getAnalysis());
                            answer.setTrueoption(questionVo.getAnswer()[0].getAnswer());
                            answerMapper.insert(answer);
                            k--;
                        }
                    }
                }

            }
            result.setCode(200);
            result.setMsg("操作成功");
        }catch (Exception e){
            result.setCode(-1);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        return result;
    }

//    public String getExamUrl(Exam exam){
//        UUID uuid = UUID.randomUUID();
//        exam.setUrl(exam.getUrl()+"/"+uuid);
//        examMapper.updateById(exam);
//        String result = exam.getUrl();
//        return result;
//    }
}
